<?php
    class Admin_NewsController extends Main_Controller_Action
    {
        private $_arrParam;
        private $_news;
        
         public function init(){
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
            $this->_news = new Admin_Model_News();
        }
        
        public function preDispatch(){
        	$auth = Zend_Auth::getInstance();
        	if(!$auth->hasIdentity()){
        		if($this->_request->getActionName() != 'login'){
        			$this->_redirect('admin/index/login');
        		}
        	}
        }
        
        public function indexAction()
        {
            $this->view->headTitle('Quản lý tin tức');
            $news = new Admin_Model_News();
            
            if($_POST['add'])
            {
                $this->_redirect('admin/news/create');
            }
            if($_POST['refresh'])
            {
                $this->_redirect('admin/news');
            }
            if($_POST['delete'])
            {
                $listId = $this->_arrParam['check'];
                $news->deleteManyNews($listId);
                $this->_redirect($_SERVER['HTTP_REFERER']);
            }
            
            $list = $news->listNews();
            $paginator = Zend_Paginator::factory($list);
            $paginator->setItemCountPerPage(40);
            $paginator->setPageRange(5);
            $currentPage = $this->_request->getParam('page', 1);
            $paginator->setCurrentPageNumber($currentPage);            
            $this->view->data = $paginator;
            $this->view->total = count($list);
            
            
            
        }
        
        public function createAction()
        {
            $this->view->headTitle('Thêm tin mới');
            $news = new Admin_Model_News();
            
            if($this->_request->isPost())
            {
                $filter = new Zend_Filter_StringTrim();
                $upload = new Zend_File_Transfer_Adapter_Http();
                
                $upload->addValidator('Size', false, 410000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                       
                $info = $upload->getFileInfo();
                $news_image = $upload->getFileName('news_image', false); // lấy tên hình của filefield "news_image"
                $news_title = $filter->filter($this->_arrParam['news_title']);
                $news_content = $filter->filter($this->_arrParam['news_content']);
                $news_plaintext = $filter->filter($this->_arrParam['news_plaintext']);
                $flag = true;
                $validator = new Admin_Form_ValidateNews();
                if(!$validator->validNewsImage($news_image))
                {
                    $this->view->errorNewsImage = 'Bạn chưa tải ảnh lên';
                    $flag = false;
                }
                
                if(!$upload->isValid())
				{
					$this->view->errorNewsImage = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng 20 byte đến 7 MB';
					$flag = false;
				}
                
                
                if($validator->validNewsTitle($news_title))
                {
                    $this->view->newsTitleValue = $news_title;
                }
                else
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin không được để trống và tối đa 300 kí tự';
                    $flag = false;
                }
                if($news->checkNews($news_title) > 0)
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin này đã tồn tại';
                    $flag = false;
                }
                
                if($validator->validNewsContent($news_content))
                {
                    $this->view->newsContentValue = $news_content;
                }
                else
                {
                    $this->view->errorNewsContent = 'Nội dung tin không được để trống tối đa 3000 ký tự tối thiểu 300 ký tự';
                    $flag = false;
                }
                
                if($flag == true)
                {
                    preg_match('#\.([^\.]+)$#', $news_image, $matches);
					$fileExtension  = $matches[1];
                    
					$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
					$options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName,'overwrite'=>true);
					$upload->addFilter('Rename',$options,'news_image');
					$upload->receive('news_image');
                    
                    $flex = new Zendvn_Filter_RemoveCircumflex();
                    $result = $news->addNews($news_title, $newFileName, $news_content, $news_plaintext);
                    $result = $news->getNewsById($result);
                    $this->_arrParam = array(
                        'news_id' => $result['news_id'],
                        'news_title' =>$news_title,
                        'news_title_filter' => $flex->filter($news_title),
                        'news_plaintext' => $news_plaintext,
                        'news_plaintext_filter' => $flex->filter($news_plaintext),
                        'news_image' => $newFileName,
                        'create_date' => $result['create_date'],
                        'status' => $result['status'],
                    );
                    $news->saveAddItem($this->_arrParam, array('task' => 'add'));
                    $this->_redirect('admin/news');
                    
                }
            }
        }
        
        public function editAction()
        {
            $this->view->headTitle('Sửa tin tức');
            $news_id = $this->_arrParam['news_id'];
            $news = new Admin_Model_News();
            $flex = new Zendvn_Filter_RemoveCircumflex();
            $this->view->data = $news->getNewsById($news_id);
            
            if($this->_request->isPost())
            {
                $filter = new Zend_Filter_StringTrim();
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                
                $news_image = $upload->getFileName('news_image', false);
                $news_title = $filter->filter($this->_arrParam['news_title']);
                $news_content = $filter->filter($this->_arrParam['news_content']);
                $news_plaintext = $filter->filter($this->_arrParam['news_plaintext']);
                $status = $this->_arrParam['status'];
                $flag = true;
                
                $validator = new Admin_Form_ValidateNews();
                if(!$validator->validNewsTitle($news_title))
                {
                    $this->view->errorNewsTitle = 'Tiêu đề tin không được để trống và tối đa 300 kí tự';
                    $flag = false;
                }
                if($this->view->data['news_title'] != $news_title)
                {
                    if($news->checkNews($news_title, $news_id) > 0)
                    {
                        $this->view->errorNewsTitle = 'Tiêu đề tin này đã tồn tại';
                        $flag = false;
                    }
                }
                if(!$validator->validNewsContent($news_content))
                {
                    $this->view->errorNewsContent = 'Nội dung tin không được để trống';
                    $flag = false;
                }
               if($flag == true)
                {
                    if(!$validator->validNewsImage($news_image))
                    {
                        $result = $news->editNews($news_id, $news_title, '', $news_content, $news_plaintext, $status);
                        $this->_arrParam = array(
                            'news_id' => $news_id,
                            'news_title' => $news_title,
                            'news_title_filter' => $flex->filter($news_title),
                            'news_plaintext' => $news_plaintext,
                            'news_plaintext_filter' => $flex->filter($news_plaintext),
                            'news_image' => $this->view->data['news_image'],
                            'create_date' => $this->view->data['create_date'],
                            'status' => $status,
                        );
                        $news->saveAddItem($this->_arrParam, array('task' => 'edit'));
                        $this->_redirect('admin/news');
                    }
                    else
                    {
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
        					$this->view->errorNewsImage = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        					$flag = false;
        				}
                        if($flag == true)
                        {
                            preg_match('#\.([^\.]+)$#', $news_image, $matches);
    						$fileExtension  = $matches[1];
    						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
    						
    						$options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName,'overwrite'=>true);
    						$upload->addFilter('Rename',$options,'news_image');
    						$upload->receive('news_image');
                            
                            $news->editNews($news_id, $news_title, $newFileName, $news_content, $news_plaintext, $status);
                            if (is_file(PUBLIC_PATH . '/files/news/' . $this->view->data['news_image']))
   							{
  								unlink(PUBLIC_PATH . '/files/news/' . $this->view->data['news_image']);
   							}
                            
                            $this->_arrParam = array(
                                'news_id' => $news_id,
                                'news_title' => $news_title,
                                'news_title_filter' => $flex->filter($news_title),
                                'news_plaintext' => $news_plaintext,
                                'news_plaintext_filter' => $flex->filter($news_plaintext),
                                'news_image' => $newFileName,
                                'create_date' => $this->view->data['create_date'],
                                'status' => $status,
                            );
                            $news->saveAddItem($this->_arrParam, array('task' => 'edit'));
   							$this->_redirect('admin/news');
                        }
                    }
                }
            }
        }
        
        public function deleteAction()
       {
            $news_id = $this->_arrParam['news_id'];
            $news = new Admin_Model_News();
            $news->deleteNews($news_id);
           $this->_redirect($_SERVER['HTTP_REFERER']);
        }
        
        
        public function searchAction()
		{
			$this->view->headTitle('Tìm kiếm tin tức');
            $filter = new Zend_Filter_StringTrim();
            $flex   = new Zendvn_Filter_RemoveCircumflex();
            $lower  = new Zend_Filter_StringToLower();
            $flag   = 0;
            $news = new Admin_Model_News();
            
			$keyword = $filter->filter($this->_arrParam['keyword']);
			$this->view->searchValue = $keyword;
			
			if($_POST['add']){
                $this->_redirect('admin/news/create');
            }
            if($_POST['refresh']){
				$this->_redirect('admin/news');
			}
            if($_POST['delete']){
                $listId = $this->_arrParam['check'];
				$this->_news->deletenewss($listId);
				$this->_redirect($_SERVER['HTTP_REFERER']);
            }
			
			$validation = new Admin_Form_Validatenews();
			if($validation->validNewsSearch($keyword))
			{
				$this->view->searchValue = $keyword;
			}
			else
            {
                $this->view->errorSearch = 'Bạn chưa nhập từ khóa';
                $keyword = 'news_title_filter:' . $keyword . ' news_plaintext:' . $keyword;
				$result = $news->searchNews($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(40);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
				$flag ++;
            }
			
			if($flag == 0)
            {
                $keyword = 'news_title_filter:' . $keyword . ' news_plaintext:' . $keyword;
                $result = $news->searchNews($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(40);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
            }		
		}
        
        
    }
